package cn.jsu.oj.judgment.net;


import cn.jsu.oj.judgment.config.ResourceConfig;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.Objects;


/**
 * 判题机客户端
 *
 *
 */
@Slf4j
@Component("judgeClient")
public class JudgeClient {

    private Bootstrap bootstrap;

    public static ChannelFuture channelFuture;

    private static final String IP = ResourceConfig.getConfigString("net.server.task.ip");

    private static final Integer PORT = ResourceConfig.getConfigInteger("net.server.task.port");

    public void init() {
        this.bootstrap = new Bootstrap();
        NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        JudgeChannelInit writeChannelInit = new JudgeChannelInit("judgeClientHandler");
        Objects.requireNonNull(this.bootstrap, "----------引导器配置失败......")
                .group(eventLoopGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .handler(writeChannelInit);
        log.info("----------判题机通道处理节点配置完成......");
    }


    public void start() {

        channelFuture = this.bootstrap.connect(IP, PORT);

        if (!channelFuture.isSuccess()) {
            channelFuture.channel().closeFuture();
            return;
        }
        try {
            channelFuture.sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }



}
